﻿using dz.loger.core;
using dz.u9.jky.schema.Common;
using dz.u9.jky.schema.SM;
using dz.util.core;
using Dz.WorkerService.Utils;
using System.Data;

namespace Dz.WorkerService.Service
{
    /// <summary>
    /// 线下退回处理
    /// </summary>
    public class RmaOffLineService : RmaBaseService
    {
        public RmaOffLineService(string processId) : base(processId)
        {
            docType = "退回处理-线下订单";
        }
        protected async override Task<DataTable> GetProcessData()
        {
            string sql = @"select id,pdate,xtype,shopcode,deptcode,org,wh,tradeno,tradeid,parent,goodsno,sellcount,sellamt,orgamt,platcode,
                        shipdate,isfit,flag,isadjust,cust,price from dz_jky_SO where flag=3 and sellcount <0 and xtype=1";

            DataTable dt = await sqlUtils.Fill(sql);

            return dt;
        }
        protected override async Task Process()
        {
            List<string> doc = dt
                     .AsEnumerable()
                     .Select(r => r.Field<string>("tradeno"))
                     .Distinct()
                     .ToList();

            
            foreach (string s in doc)
            {
                LogUtil.Instance.Debug(s);
                await Import(s);
            }

        }

        private async Task Import(string docNo)
        {
            DataRow[] rows = dt.Select($"tradeno='{docNo}'");

            string cust = rows[0]["cust"].ToString();
            string org = rows[0]["org"].ToString();
            string tradeid = rows[0]["tradeid"].ToString();
            string dept = rows[0]["deptcode"].ToString();
            string wh = WarehouseUtils.Instance.GetRtnWh(org); ;
            string extWhere = $" and tradeid = '{tradeid}'";

            if (!CustUtils.Instance.IsExists(cust, org))
            {
                LogUtil.Instance.Debug($"{docNo} 客户 {cust} 在U9中不存在，跳过");
                await UpdateDataState(2, extWhere);
                return;
            }

            DzRMA rma = new DzRMA();

            rma.DocumentType = documentType;
            rma.Customer = cust;
            rma.Org = org;
            rma.TC = currencys[rma.Org];
            rma.AC = rma.TC;
            rma.BusinessDate = Convert.ToDateTime(rows[0]["shipdate"]);
            rma.Org = org;
            rma.SaleDept = dept;
            string taxSchedule = TaxScheduleUtils.Instance.GetTaxSchedule(dept, org);

            DescFlexField desc = new DescFlexField();
            desc.PubDescSeg8 = docNo;

            rma.DescFlexField = desc;


            List<DzRMALine> lines = new List<DzRMALine>();
            foreach (DataRow row in rows)
            {
                DzRMALine line = new DzRMALine();

                string inv = row["goodsno"].ToString();

                if (!InvUtils.Instance.IsExists(inv, org))
                {
                    LogUtil.Instance.Debug($"存货{inv} 在U9中不存在，跳过");
                    continue;
                }

                line.ItemInfo = inv;
                line.ApplyQtyTU1 = Math.Abs(Convert.ToDecimal(row["sellcount"]));
                line.RtnQtyTU1 = line.ApplyQtyTU1;
                line.Warehouse = wh;
                if (taxSchedule.Length > 0) line.TaxSchedule = taxSchedule;

                decimal amt = Math.Abs(Convert.ToDecimal(row["sellamt"]));
                decimal qty = Math.Abs(Convert.ToDecimal(row["sellcount"]));
                decimal price = Math.Round(amt / qty, 6);
                line.OrderPrice = price;
                line.ApplyPrice = price;
                line.RtnMoneyTC = amt;

                DescFlexField desc1 = new DescFlexField();
                desc1.PubDescSeg8 = docNo;
                line.DescFlexField = desc1;

                lines.Add(line);
            }

            if (lines.Count == 0)
            {
                await UpdateDataState(2, extWhere);
                return;
            }

            rma.RMALines = lines;

            //U9CResult result = await U9Utils.Post(controller, "AddAndAudit", JsonUtil.Serialize(ship));

            U9CResult result = await U9Utils.Post(controller, "Add", JsonUtil.Serialize(rma));

            await UpdateSyncLog(result, extWhere);

        }
    }
}
